import { app, shell, BrowserWindow, ipcMain, screen } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'

function createWindow(): void {
  const mainWindow = new BrowserWindow({
    width: 200,
    height: 200,
    show: false,
    autoHideMenuBar: true,
    frame: false, // 保持无边框
    transparent: true,
    alwaysOnTop: true,
    resizable: false,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      nodeIntegration: false,
      contextIsolation: true
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  let x = 0
  let y = 0
  let x1 = 0
  let y1 = 0
  let winW = 0
  let winH = 0

  // 添加窗口拖动IPC处理
  ipcMain.handle('start-drag', () => {
    const point = screen.getCursorScreenPoint()
    x = point.x
    y = point.y
    const bounds = mainWindow.getBounds()
    x1 = x - bounds.x
    y1 = y - bounds.y
    winW = bounds.width
    winH = bounds.height
    return { success: true }
  })

  // 优化的拖动处理
  ipcMain.handle('drag-window', () => {
    const point = screen.getCursorScreenPoint()
    x = point.x - x1
    y = point.y - y1
    // 计算所有屏幕组成的大矩形区域
    const allDisplays = screen.getAllDisplays()
    const screenBounds = allDisplays.reduce(
      (acc, display) => {
        const bounds = display.bounds
        acc.minX = Math.min(acc.minX, bounds.x)
        acc.maxX = Math.max(acc.maxX, bounds.x + bounds.width)
        acc.minY = Math.min(acc.minY, bounds.y)
        acc.maxY = Math.max(acc.maxY, bounds.y + bounds.height)
        return acc
      },
      {
        minX: Infinity,
        maxX: -Infinity,
        minY: Infinity,
        maxY: -Infinity
      }
    )

    const currentDisplay = screen.getDisplayNearestPoint({ x, y })
    const workArea = currentDisplay.workArea

    const mouseRange = { minX: 0, maxX: 0, minY: 0, maxY: 0 } // 所有窗口的范围
    mouseRange.minX = screenBounds.minX // 最小X坐标向左偏移68像素
    mouseRange.maxX = screenBounds.maxX // 最大X坐标向右偏移68像素
    mouseRange.minY = workArea.y // 最大X坐标向右偏移68像素
    mouseRange.maxY = workArea.height + workArea.y // 最大X坐标向右偏移68像素

    if (x < mouseRange.minX) x = mouseRange.minX
    if (x + winW > mouseRange.maxX) x = mouseRange.maxX - winW

    if (y < mouseRange.minY) y = mouseRange.minY
    if (y + winH > mouseRange.maxY) y = mouseRange.maxY - winH

    // 设置窗口位置
    mainWindow.setBounds({ x, y, width: winW, height: winH })
  })

  ipcMain.handle('stop-drag', () => {
    return { success: true }
  })
}

app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
